package com.younio.local.compnent.datasource;

import com.younio.local.annotation.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.younio.local.repository.*.*(..))")
    public void aspect() {
    }

    @Before(value = "aspect()")
    public void before(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String targetDatasource;
        if (MultiDataSourceHolder.contains(method)) {
            targetDatasource = MultiDataSourceHolder.get(method);
        } else {
            DataSource source = method.getDeclaredAnnotation(DataSource.class);
            if (source == null) {
                Class<?> methodDeclaringClass = method.getDeclaringClass();
                source = methodDeclaringClass.getDeclaredAnnotation(DataSource.class);
                if (source == null) {
                    throw new RuntimeException("请通过@DataSource注解设置" + method.getName() + "使用的数据源");
                }
            }
            targetDatasource = MultiDataSourceHolder.get(source.value());
            MultiDataSourceHolder.put(method, targetDatasource);
        }

        MultiDataSourceHolder.set(targetDatasource);
    }
}
